/*
 * @Author: Zhengxuan Ye
 * @Date: 2025-05-06 21:28:51
 * @Last Modified by:   Zhengxuan Ye
 * @Last Modified time: 2025-05-06 21:28:51
 */

import { defineStore } from 'pinia'
import axios from 'axios'

// API基础URL
const API_URL = 'http://localhost:3000/api'

export const useInteractionStore = defineStore('interaction', {
  state: () => ({
    comments: {},
    likes: {},
    shares: {},
    loading: false,
    error: null,
  }),

  actions: {
    // 重置特定页面的状态
    resetPageState(pageId) {
      console.log(`重置页面ID: ${pageId} 的状态`)
      if (pageId) {
        // 重置特定页面的状态
        delete this.comments[pageId]
        delete this.likes[pageId]
        delete this.shares[pageId]
      } else {
        // 重置所有状态
        this.comments = {}
        this.likes = {}
        this.shares = {}
      }
      this.error = null
    },

    // 获取页面评论
    async getComments(pageId) {
      try {
        this.loading = true
        const response = await axios.get(`${API_URL}/interaction/comments/${pageId}`)

        // 使用对象设置评论，以页面ID为键
        this.comments = {
          ...this.comments,
          [pageId]: response.data.comments,
        }

        this.loading = false
        return response.data.comments
      } catch (error) {
        console.error('获取评论失败:', error)
        this.error = error.response?.data?.message || '获取评论失败'
        this.loading = false
        return []
      }
    },

    // 添加评论
    async addComment(pageId, content, token) {
      try {
        this.loading = true
        console.log(
          '发送评论请求，URL:',
          `${API_URL}/interaction/comment`,
          '数据:',
          { pageId, content },
          '令牌:',
          token,
        )

        const response = await axios.post(
          `${API_URL}/interaction/comment`,
          { pageId, content },
          {
            headers: { Authorization: `Bearer ${token}` },
            withCredentials: true,
          },
        )

        console.log('评论响应:', response.data)

        // 更新评论列表
        if (!this.comments[pageId]) {
          this.comments[pageId] = []
        }

        this.comments[pageId].unshift(response.data.comment)
        console.log('更新后的评论列表:', this.comments[pageId])

        this.loading = false
        return response.data.comment
      } catch (error) {
        console.error('添加评论失败:', error)
        this.error = error.response?.data?.message || '添加评论失败'
        this.loading = false
        return null
      }
    },

    // 点赞/取消点赞
    async toggleLike(pageId, token) {
      try {
        this.loading = true
        console.log(
          '发送点赞请求，URL:',
          `${API_URL}/interaction/like`,
          '数据:',
          { pageId },
          '令牌:',
          token,
        )

        const response = await axios.post(
          `${API_URL}/interaction/like`,
          { pageId },
          {
            headers: { Authorization: `Bearer ${token}` },
            withCredentials: true,
          },
        )

        console.log('点赞响应:', response.data)

        // 更新点赞状态
        this.likes = {
          ...this.likes,
          [pageId]: {
            liked: response.data.liked,
            count: response.data.likesCount,
          },
        }

        console.log('更新后的点赞状态:', this.likes[pageId])

        this.loading = false
        return this.likes[pageId]
      } catch (error) {
        console.error('点赞操作失败:', error)
        this.error = error.response?.data?.message || '点赞操作失败'
        this.loading = false
        return null
      }
    },

    // 检查点赞状态
    async checkLikeStatus(pageId, token) {
      try {
        this.loading = true

        // 创建请求配置，只有在有token时才添加Authorization头
        const config = token
          ? { headers: { Authorization: `Bearer ${token}` }, withCredentials: true }
          : { withCredentials: true }

        console.log('检查点赞状态，token:', token ? '已提供' : '未提供')
        const response = await axios.get(`${API_URL}/interaction/like/${pageId}`, config)
        console.log('点赞状态响应:', response.data)

        // 更新点赞状态
        this.likes = {
          ...this.likes,
          [pageId]: {
            liked: response.data.liked,
            count: response.data.count,
          },
        }

        this.loading = false
        return this.likes[pageId]
      } catch (error) {
        console.error('检查点赞状态失败:', error)
        // 游客或未登录用户
        this.likes = {
          ...this.likes,
          [pageId]: {
            liked: false,
            count: 0,
          },
        }

        this.loading = false
        return this.likes[pageId]
      }
    },

    // 分享页面
    async sharePage(pageId, token) {
      try {
        this.loading = true
        const response = await axios.post(
          `${API_URL}/interaction/share`,
          { pageId },
          {
            headers: { Authorization: `Bearer ${token}` },
            withCredentials: true,
          },
        )

        // 更新分享状态
        this.shares = {
          ...this.shares,
          [pageId]: response.data.sharesCount,
        }

        this.loading = false
        return response.data.sharesCount
      } catch (error) {
        console.error('分享失败:', error)
        this.error = error.response?.data?.message || '分享失败'
        this.loading = false
        return null
      }
    },

    // 获取分享数
    async getSharesCount(pageId) {
      try {
        this.loading = true
        const response = await axios.get(`${API_URL}/interaction/shares/${pageId}`)

        // 更新分享数
        this.shares = {
          ...this.shares,
          [pageId]: response.data.sharesCount,
        }

        this.loading = false
        return response.data.sharesCount
      } catch (error) {
        console.error('获取分享数失败:', error)
        this.error = error.response?.data?.message || '获取分享数失败'
        this.loading = false
        return 0
      }
    },
  },
})
